package com.xiaoge.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoge.response.Result;
import com.xiaoge.response.ResultCode;
import com.xiaoge.system.entity.Department;
import com.xiaoge.system.entity.User;
import com.xiaoge.system.mapper.DepartmentMapper;
import com.xiaoge.system.mapper.UserMapper;
import com.xiaoge.system.service.DepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoge
 * @since 2021-02-02
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Department findDeptById(Long id) {
        return departmentMapper.selectById(id);
    }

    /**
     * 查询部门人数
     * @return
     */
    @Override
    public List<Department> findDeptAndCount() {
        return this.baseMapper.findDeptAndCount();
    }

    /**
     * 查询部门
     * @param queryWrapper
     * @return
     */
    @Override
    public List<Department> getDeptAndCount(QueryWrapper<Department> queryWrapper) {
        return this.baseMapper.getDeptAndCount( queryWrapper);
    }

    /**
     * 添加部门
     * @param department
     * @return
     */
    @Override
    public Result addDept(Department department) {
        QueryWrapper<Department>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",department.getName());
        Integer integer=departmentMapper.selectCount(queryWrapper);
        if (integer!=0){
            return Result.error(ResultCode.DEPARTMENT_ALREADY_EXIST);
        }
        departmentMapper.insert(department);
        return Result.ok();
    }

    /**
     * 修改部门
     * @param department
     * @return
     */
    @Override
    public Result updateDept(Department department) {
        departmentMapper.updateById(department);
        return Result.ok();
    }

    /**
     * 删除部门
     * @param id
     * @return
     */
    @Override
    public Result deleteDept(Long id) {
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("department_id",id);
        Integer integer=userMapper.selectCount(queryWrapper);
        if (integer!=0){
            return Result.error(ResultCode.DEPARTMENT_HAVE_USER);
        }
        departmentMapper.deleteById(id);
        return Result.ok();
    }

}
